import {RequestHandler} from 'express-serve-static-core';
import merge from 'lodash/merge';
import {SEARCH_KEY} from '../../src/utils/constant';

const analyzeRequestType: RequestHandler = async (req, res, next) => {
	const {query} = req;
	// 检查 预览/编辑 模式
	const isEditing = query[SEARCH_KEY.编辑模式] === '1';
	const isPreview = query[SEARCH_KEY.预览模式] === '1';
	const previewId = isEditing || isPreview ? query[SEARCH_KEY.模板ID] || null : null;
	if ((isPreview || isEditing) && !previewId) return res.status(404).end();
	// 检查渲染类型
	const pcMode = query[SEARCH_KEY.桌面端模式] === '1';
	const mobileMode = query[SEARCH_KEY.移动端端模式] === '1';
	const ua = req.header('user-agent');
	const pcUA = !/mobile/i.test(ua);
	const isPc = isEditing || isPreview ? (mobileMode ? false : pcMode ? true : pcUA) : pcUA;
	const isMobile = !isPc;
	const isApp = !isPc && (/tradechina/i.test(ua) || /wzm/i.test(ua));
	// 注入配置项
	merge(req.meoData, {isPc, isMobile, isApp, isEditing, isPreview, previewId});
	next();
};

export default analyzeRequestType;
